package com.ipzoe.file.config;

import com.ipzoe.file.config.properties.FileServerProperties;
import com.ipzoe.file.domain.FileInfoDO;
import com.ipzoe.file.service.AbstractFileDOService;
import com.ipzoe.file.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author Eric
 * @date 2020/6/12
 */
@Configuration
@EnableConfigurationProperties(FileServerProperties.class)
@ConditionalOnProperty(prefix = "ruoyi.file-server", name = "type", havingValue = "local")
public class FileLocalAutoConfigure {

    @Autowired
    private FileServerProperties fileServerProperties;

    @Service
    public class FileLocalDOServiceImpl extends AbstractFileDOService {

        /**
         * 文件来源
         *
         * @return
         */
        @Override
        protected String fileType() {
            return fileServerProperties.getType();
        }

        /**
         * 上传文件
         *
         * @param file
         * @param fileInfo
         * @author Eric
         * @date 2020/3/25
         */
        @Override
        protected void uploadFile(MultipartFile file, FileInfoDO fileInfo) throws IOException {
            FileUtil.saveFile(file, fileServerProperties.getLocal().getBasePath() + fileInfo.getPath());
            fileInfo.setUrl(
                    fileServerProperties.getLocal().getWebUrl() + "/" + fileInfo.getPath().replace(File.separator, "/"));
            fileInfo.setPath(fileServerProperties.getLocal().getBasePath() + fileInfo.getPath());
        }

        /**
         * 删除文件资源
         *
         * @param fileInfo
         * @return
         */
        @Override
        protected boolean deleteFile(FileInfoDO fileInfo) {
            FileUtil.deleteFile(fileInfo.getPath());
            return true;
        }
    }
}

